import 'dart:async';
import 'dart:convert' as convert;
// import 'dart:convert';
import 'dart:developer';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_syt/generated/assets.dart';
import 'package:flutter_syt/widgets/auto_image.dart';
// import 'package:fluwx/fluwx.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/domain/widgets/common_dialog.dart';
import 'package:flutter_syt/domain/widgets/custom_dialog.dart';
import 'package:flutter_syt/entity/order_ailpay_entity.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/global_easy_loading.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/utils_dlog.dart';
import 'package:flutter_syt/utils/utils_other.dart';
import 'package:flutter_syt/widgets/web_html.dart';
// import 'package:tobias/tobias.dart';
// import 'package:tobias/tobias.dart' as Tobias;
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

@RoutePage(name: "paymentDesk")
class paymentDeskPage extends StatefulWidget {
  final String dataInfo;

  final payItems = [
    PayType('assets/icons/pay_wechat.png', S().pay_wechat, '2'),
    PayType('assets/icons/pay_alipay.png', S().pay_alipay, '3'),
    PayType('assets/icons/pay_card.png', S().pay_bankcard, '1'),
    PayType('assets/icons/pay_digital.png', S().pay_digital, '4'),
    PayType('assets/icons/pay_other.png', S().pay_other, '5'),
    // pay_other
  ];

  paymentDeskPage(this.dataInfo);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _paymentDeskState();
  }
}

class _paymentDeskState extends State<paymentDeskPage> {
  var orderId = '';
  var totalFee = '';
  var goods = '';
  // StreamSubscription<BaseWeChatResponse>? wxSubscription;
  // bool isNeedCheck = false;
  PayType? currentType;
  List<PayType> supportType = [];

  @override
  void initState() {
    super.initState();
    // wxSubscription = weChatResponseEventHandler.listen((event) {
    //   if (event.errCode == 0) {
    //     _onPopRequest();
    //   }
    // });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    // wxSubscription?.cancel();
    // wxSubscription = null;
  }

  @override
  Widget build(BuildContext context) {
    Map<String, dynamic> json = convert.jsonDecode(widget.dataInfo);
    orderId = "${json["order_id"]}";
    totalFee = "${json["total_fee"]}";
    goods = "${json["body"]}";
    if (supportType.isEmpty) {
      var type = "${json["pay_mode"]}".split(',');
      for (final item in widget.payItems) {
        for (final typeStr in type) {
          if (typeStr == item.type) {
            supportType.add(item);
          }
        }
      }
      if (supportType.isEmpty) {
        supportType = widget.payItems;
      }
    }
    return WillPopScope(
      onWillPop: () async {
        return _onPopRequest();
      },
      child: Scaffold(
        appBar: AppBar(
          title: Text(''),
        ),
        body: Container(
          child: Column(
            children: [
              _moneyColumn(),
              _payColumn(),
              _submitBtn(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _submitBtn() {
    return Container(
      margin: const EdgeInsets.only(top: 10, bottom: 0),
      padding: EdgeInsets.only(left: 16, right: 16),
      width: double.infinity,
      child: ElevatedButton(
          child: Text(
            S.of(context).pay_confirm,
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
          onPressed: ClickUtils.debounce(
            () async {
              if (currentType == null) {
                customShowToast(S.of(context).pay_way);
              } else {
                if (currentType?.type == '3') {
                  // Tobias().isAliPayInstalled
                  // bool isInstall = await Tobias().isAliPayInstalled;
                  // if (!isInstall) {
                  //   customShowToast(S.of(context).pay_no_alipay);
                  //   return;
                  // }
                } else if (currentType?.type == '2') {
                  // bool isInstall = await isWeChatInstalled;
                  // if (!isInstall) {
                  //   customShowToast(S.of(context).pay_no_alipay);
                  //   return;
                  // }
                }
                _onSubmit();
              }
            },
          )),
    );
  }

  Future<bool> _onPopRequest() async {
    EasyLoading.instance.loadingStyle = EasyLoadingStyle.light;
    EasyLoading.show(
      status: S().loading,
      maskType: EasyLoadingMaskType.black,
      indicator: const AutoImage(
        Assets.loading,
        width: 64,
        height: 64,
      )
    );

    var isSuccess = '1';
    try {
      bool preSuccess = await getprePayOrderInfo(orderId);
      // if (isNeedCheck) {
      //   if (preSuccess == false) {
      //     await Future.delayed(Duration(seconds: 3));
      //     preSuccess = await getprePayOrderInfo(orderId);
      //     if (preSuccess == false) {
      //       await Future.delayed(Duration(seconds: 3));
      //       preSuccess = await getprePayOrderInfo(orderId);
      //     }
      //   }
      // }
      isSuccess = preSuccess ? '1' : '0';
    } catch (e) {
      isSuccess = '0';
    }
    Navigator.of(context).pop("$isSuccess");
    EasyLoading.dismiss();
    return true;
  }

  Future<bool> getprePayOrderInfo(orderId) async {
    var json = await API.shared.bridge.prePayOrderInfo(orderId);
    var status = json["pay_status"] as int;
    return status == 1;
  }

  void _onSubmit() async {
    try {
      var result = Map();
      try {
        result =
            await API.shared.bridge.appPay(orderId, currentType?.type ?? "");
      } catch (e) {
        await UtilsOther.showCustomShowError(e);
        return;
      }
      var payData = '';
      // convert.jsonEncode(result);
      log(convert.jsonEncode(result));

      if (currentType?.type == '1' ||
          currentType?.type == '4' ||
          currentType?.type == '5') {
        payData = "${result["pay_data"]}";

        showCommonDialog(
            context,
            DialogEntity(S().permission_tips, Text(S().pay_tips),
                () => Navigator.of(context).pop(), () async {
              Navigator.of(context).pop();
              await Future.delayed(Duration.zero);
              // isNeedCheck = true;
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => WebHtmlPage(
                            payData,
                            orderId: orderId,
                          ))).then((value) {
                if (value is bool) {
                  Navigator.of(context).pop("$value");
                } else {
                  Navigator.of(context).pop(false);
                }
              });
            }, cancelText: S.of(context).cancel, okText: S.of(context).sure));
      } else if (currentType?.type == '2') {
        Map payData = result['pay_data'];
        Map packageValue = convert.jsonDecode(payData['wx_data_package']);
        DLog(payData);
        DLog(packageValue);
        // wx:///    window.
        // topay
        // await registerWxApi(
        //     appId: packageValue['appid'],
        //     universalLink: "https://app.api.2021chengdu.com/app/");
        // payWithWeChat(
        //     appId: packageValue['appid'],
        //     partnerId: packageValue['partnerid'],
        //     prepayId: packageValue['prepayid'],
        //     packageValue: packageValue['package'],
        //     nonceStr: packageValue['noncestr'],
        //     timeStamp: int.parse(packageValue['timestamp']),
        //     sign: packageValue['sign']);
      } else if (currentType?.type == '3') {
        OrderAilpayEntity entity = OrderAilpayEntity.fromJson(result.cast());
        if ((entity.payData?.zfbDataPackage ?? '').isEmpty) {
          customShowToast(
              entity.payData?.returnMsg ?? S.of(context).pay_no_support);
          return;
        }
        payData = "${result["zfb_data_package"]}";
        // OrderAilpayEntity entity = OrderAilpayEntity.fromJson(result.cast());
        // var map = await Tobias().auth(entity.payData?.zfbDataPackage ?? '');
        // // var msg = "";
        // log(map.toString());
        var status = "";
        try {
          // status = map["resultStatus"] as String;
        } catch (e) {}
        if (status == '9000') {
          _onPopRequest();
        } else {
          // try {
          //   msg = map["memo"] as String;
          // } catch (e) {}
          // if (msg.isNotEmpty) {
          //   customShowToast(msg);
          // }
        }
      } else {
        customShowToast(S.of(context).pay_no_support);
        return;
      }
    } catch (e) {
      await UtilsOther.showCustomShowError(e);
      // if (e is DioError) {
      //   customShowToast(e.message);
      // } else {
      //   customShowToast(S().network_error);
      // }
    }
  }

  Container _moneyColumn() {
    return Container(
      // color: Colors.red,
      alignment: Alignment.bottomCenter,
      padding: EdgeInsets.fromLTRB(16, 10, 16, 0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          RichText(
            textAlign: TextAlign.center,
            text: TextSpan(
              children: [
                TextSpan(
                  text: "¥",
                  style: TextStyle(
                    fontSize: 24,
                    color: Colors.black,
                    fontFamily: 'PingFang SC',
                    fontWeight: FontWeight.w600,
                  ),
                ),
                TextSpan(
                  text: totalFee,
                  style: TextStyle(
                    fontSize: 48,
                    color: Colors.black,
                    fontFamily: 'PingFang SC',
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ),
          ),
          SizedBox(
            height: 10,
          ),
          // Text(
          //   '$goods',
          //   textAlign: TextAlign.center,
          //   style: TextStyle(
          //     color: ThemeColor.colorBlack60,
          //     fontFamily: 'PingFang SC',
          //   ),
          // ),
          // SizedBox(
          //   height: 24,
          // ),
          Container(
            child: Align(
              alignment: Alignment.bottomCenter,
              child: Divider(
                height: 1,
              ),
            ),
          )
        ],
      ),
    );
  }

  Container _payColumn() {
    return Container(
      padding: EdgeInsets.fromLTRB(16, 16, 16, 16),
      child: Column(
        // mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            S.of(context).pay_way,
            style: TextStyle(
              fontSize: 20,
              fontFamily: 'PingFang SC',
              fontWeight: FontWeight.w500,
            ),
          ),
          SizedBox(
            height: 20,
          ),
          for (var item in supportType) _payRow(item),
        ],
      ),
    );
  }

  Widget _payRow(PayType data) {
    return Column(
      children: [
        Container(
          child: GestureDetector(
              onTap: ClickUtils.debounce(() {
                setState(() {
                  currentType = data;
                });
              }),
              behavior: HitTestBehavior.opaque,
              child: Row(
                children: [
                  Image.asset(
                    data.icon,
                    width: 32,
                    height: 32,
                  ),
                  SizedBox(
                    width: 15,
                  ),
                  Text(data.title),
                  Spacer(),
                  Image.asset(
                    currentType?.type == data.type
                        ? 'assets/icons/pay_box_select.png'
                        : 'assets/icons/pay_box_normal.png',
                    width: 20,
                    height: 20,
                  ),
                ],
              )),
        ),
        SizedBox(
          height: 30,
        ),
      ],
    );
  }
}

class PayType {
  String icon;
  String title;
  String type;

  PayType(this.icon, this.title, this.type);
}
